import React from 'react';
import { connect } from 'dva';
import { Table, Pagination, Popconfirm, Button } from 'antd';
import {routerRedux} from 'dva/router';
import { PAGE_SIZE } from '../../constants';
import styles from './Users.css';
import UserModal from './UserModal';

function Users({dispatch,list:dataSource,loading,total,page:current}) {
  function pageChangeHandler(page){
    dispatch(routerRedux.push({
      pathname:'/users',
      query:{page}
    }));
  }

  function createHandler(values) {
    dispatch({
      type: 'users/create',
      payload: values
    });
  }

  function editHandler(id,values) {
    console.log(id+"---"+values);
    dispatch({
      type: 'users/patch',
      payload: {id,values}
    });
  }
  function deleteHandler(id) {
    console.log(id);
    dispatch({
      type: 'users/remove',
      payload: {id}
    });
  }

 const columns = [
    {
      title: 'id',
      dataIndex: 'id',
      key: 'id',
      width:'200px',
      render:  text =><a href=""  >{text}</a>,
    },
    {
      title: 'name',
      dataIndex: 'name',
      key: 'name',
    },
    {
      title: 'age',
      dataIndex: 'age',
      key: 'age',
    },
     {
      title: 'phone',
      dataIndex: 'phone',
      key: 'phone',
    },
    {
      title: 'Operation',
      key: 'operation',
      render: (text, record) => (
         <span>
            <UserModal onOk={editHandler.bind(null, record.id)} record={record}  >
              <a>Edit</a>
            </UserModal>

            <Popconfirm title="Confirm to delete?" onConfirm={deleteHandler.bind(null,record.id)} >
              <a href="">Delete</a>
            </Popconfirm>
          </span>
      )
    },
  ];

  return (
    <div className={styles.normal}>
       <div>
        <UserModal onOk={createHandler} record={{}}  >
          <div><Button type="danger">Create User</Button></div>
        </UserModal>
        <Table
            columns={columns}
            dataSource={dataSource}
            loading={loading}
            rowKey={record => record.id}
            pagination={false}
          />
          <Pagination
            className="ant-table-pagination"
            total={total}
            current={current}
            pageSize={PAGE_SIZE}
            onChange={pageChangeHandler}
          />
         </div>
    </div>
  );
}

function mapStateToProps(state) {
  console.log("state:"+state.users);
  const { list, total, page } = state.users;
  return {
    loading: state.loading.models.users,
    list,
    total,
    page,
  };
}


export default connect(mapStateToProps)(Users);
